const { maindb } = require('../utils/db.js')
const mongoose = require('mongoose');
const { SensitiveWord } = require('./sensitiveWord');
const { redisGet } = require('../utils/redis');

const msgSchema = new mongoose.Schema({
    user: { type: String, required: true }, // 用户imKey
    toUser: { type: String, required: true }, // 对方imKey
    msg: { type: Object, default: {} }, // 消息
    read: { type: Boolean, default: false }, // 是否已读
    msgKey: { type: String, required: true }, // 消息key
    createTime: { type: Date, default: Date.now }, // 创建时间
});

const Msg = maindb.model('Msg', msgSchema);

// 添加
const createMsg = async (msg) => {
    try {
        const result = await Msg.create(msg);
        return Promise.resolve(result);
    } catch (error) {
        return Promise.reject(error);
    }
}

// 获取聊天记录列表,db中user=参数user或者DB中toUser=参数user。按时间降序。并返回数据总页数
const getChatHistory = async (user, toUser, page, pageSize) => {
    console.log('getChatHistory', user, toUser, page, pageSize)
    try {
        // 确保 page 和 pageSize 是数字类型
        const currentPage = parseInt(page) || 1;
        const limit = parseInt(pageSize) || 10;
        const list = await Msg.find({
            $or: [
                {
                    $and: [{ user }, { toUser: toUser }]
                },
                {
                    $and: [{ toUser: user }, { user: toUser }]
                }
            ]
        }).sort({ createTime: -1 }).skip((currentPage - 1) * limit).limit(limit);
        const total = await Msg.countDocuments({
            $or: [
                {
                    $and: [{ user }, { toUser: toUser }]
                },
                {
                    $and: [{ toUser: user }, { user: toUser }]
                }
            ]
        });
        return Promise.resolve({
            list,
            total,
            totalPages: Math.ceil(total / pageSize)
        });
    } catch (error) {
        return Promise.reject(error);
    }
}

// 批量设置已读
const setRead = async (msgKeys) => {
    await Msg.updateMany({ msgKey: { $in: msgKeys } }, { $set: { read: true } });
}

// 列表查询
const getMsgList = async (params) => {
    try {
        const { user, toUser, page, pageSize } = params;
        const result = await Msg.find({ $or: [{ user }, { toUser: user }] }).sort({ createTime: -1 }).skip((page - 1) * pageSize).limit(pageSize);
        const total = await Msg.countDocuments({ $or: [{ user }, { toUser: user }] });
        return Promise.resolve({
            list: result,
            total,
            totalPages: Math.ceil(total / pageSize)
        });
    } catch (error) {
        return Promise.reject(error);
    }
}

// 分页查询包含敏感词的消息列表
const getMsgContentList = async (params) => {
    try {
        const { page, pageSize, keyWord } = params;

        if (!keyWord) {
            return Promise.resolve({
                list: [],
                total: 0,
                totalPages: 0
            });
        }

        // 查找包含敏感词的消息
        const result = await Msg.find({
            'msg.content': { $regex: keyWord }
        }).sort({ createTime: -1 }).skip((page - 1) * pageSize).limit(pageSize);

        const total = await Msg.countDocuments({
            'msg.content': { $regex: keyWord }
        });

        // 处理列表数据，添加用户信息
        const list = JSON.parse(JSON.stringify(result));
        for (let i = 0; i < list.length; i++) {
            const userInfo = await redisGet(`mim-${list[i].user}`);
            const toUserInfo = await redisGet(`mim-${list[i].toUser}`);
            list[i].userInfo = userInfo || null;
            list[i].toUserInfo = toUserInfo || null;
        }

        return Promise.resolve({
            list,
            total,
            totalPages: Math.ceil(total / pageSize)
        });
    } catch (error) {
        return Promise.reject(error);
    }
}

// 用户获取客服消息，查询user或toUser等于传参user得所有消息不分页
const getServiceChatHistoryMsg = async (user, pageParams) => {
    try {
        const { page = 1, pageSize = 20 } = pageParams;
        const result = await Msg.find({
            $and: [
                { $or: [{ user }, { toUser: user }] },
                { $or: [{ "msg.fromType": 3 }, { "msg.toType": 3 }] }
            ]
        }).sort({ createTime: -1 }).skip((Number(page) - 1) * Number(pageSize)).limit(Number(pageSize));
        const total = await Msg.countDocuments({
            $and: [
                { $or: [{ user }, { toUser: user }] },
                { $or: [{ "msg.fromType": 3 }, { "msg.toType": 3 }] }
            ]
        });
        return Promise.resolve({
            list: result,
            total,
            totalPages: Math.ceil(total / pageSize)
        });
    } catch (error) {
        return Promise.reject(error);
    }
}

// 获取指定用户发送给我的和我回复给他的最新的两条消息
const getLatestMsg = async (user, toUser) => {
    const result = await Msg.find({
        $or: [
            { user: user, toUser: toUser },
            { user: toUser, toUser: user }
        ]
    }).sort({ createTime: -1 }).limit(2);
    return Promise.resolve(result);
}

module.exports = {
    createMsg,
    getChatHistory,
    setRead,
    getMsgList,
    getMsgContentList,
    getServiceChatHistoryMsg
}



